﻿using AutoMapper;
using CommonClass;
using I_Produce.API.Application.Commands.BreedingMotherCommand;
using I_Produce.Domains.DTO;
using I_Produce.Domains.Entity;
using I_Produce.Infrastructure.Interface;
using MediatR;
using Newtonsoft.Json;

namespace I_Produce.API.Application.CommandHandlers.BreedingMotherHandler
{
	public class BreedingMotherCreateCommandHandler : IRequestHandler<BreedingMotherCreateCommand, ApiResult<int>>
	{
		private readonly IMapper _mapper;
		private readonly IBreedingMotherRepository _repository;
		private readonly Cross_services_Helper _httpClient;

		public BreedingMotherCreateCommandHandler(IMapper mapper, IBreedingMotherRepository repository, Cross_services_Helper httpClient)
		{
			_mapper = mapper;
			_repository = repository;
			_httpClient = httpClient;
		}

		public async Task<ApiResult<int>> Handle(BreedingMotherCreateCommand request, CancellationToken cancellationToken)
		{
			var brddding = _mapper.Map<BreedingMother>(request);

			var result = await _repository.AddAsync(brddding);

			if (result > 0)
			{
				var germlineHistory = new GermlineHistoryRecords
				{
					MotherEarHorn = request.Auricle,
					BreedEarHorn = request.FirstWithRam,
					DateOfBreeding = request.DateOfBreeding
				};

				await _httpClient.Post("http://10.31.56.22:8000/ProduceSetRout/api/GermlineHistoryRecords/AddGermlineHistoryRecords", germlineHistory);

				var spermatophore = await _httpClient.Get("http://10.31.56.22:8000/ArchivesGetRout/api/Archives/ArchivesGetByEarNumberInfo?EarNumber=" + request.Auricle);

				var dto = JsonConvert.DeserializeObject<BreedDTO>(spermatophore);
				var SheepBreed = dto.SheepBreed;
				var Sex = dto.SheepGender;

				var sheepRescission = new SheepRescission
				{
					RoundType = "种母配种转舍",
					SurrenderDate = request.DateOfBreeding,
					Breed = SheepBreed,
					Sex = Sex,
					TurnBuilding = request.CurrentBuilding,
					TransferBuilding = request.TransferBuilding,
					RolloutField = request.CurrentField,
					DriveField = request.DriveField,
					VisualEarSignal = request.Auricle
				};

				await _httpClient.Post("http://10.31.56.22:8000/ProduceSetRout/api/SheepRescission/AddSheepSheepRescission", sheepRescission);

				return new ApiResult<int>
				{
					Code = 200,
					msg = "成功",
					Data = result
				};
			}

			return new ApiResult<int>
			{
				Code = 201,
				msg = "失败",
				Data = result
			};
		}
	}
}
